package com.nunbey.lingxi.config.lincat.spring.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;


/**
 * @description 邮寄发送工具
 * @author lincat
 */
@Component
public class MailUtil {


    /**
     * 邮件发送者
     */
    @Value("${spring.mail.username}")
    private String sender;
    //private String sender = "2596874177@qq.com";
    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 生成bitNumber位的随机数
     * @param bitNumber
     * @return
     */
    public String generateVerificationCode(int bitNumber){
       int perNumber;
       StringBuilder stringBuilder = new StringBuilder();
       for(int i=0;i<bitNumber;i++){
           perNumber = (int) (Math.random() * 9) +1;
           stringBuilder.append(perNumber);
       }
       return stringBuilder.toString();
    }

    /**
     * @description 异步发送简单内容的邮件
     * @param mail
     */
    public void sendSimpleEmail(MailBean mail){
        SendEmailTask sendEmailTask = new SendEmailTask(mail);
        sendEmailTask.run();
    }

    /**
     * 异步发送邮件的任务容器
     */
    private class SendEmailTask implements Runnable{
        private MailBean mail;
        SendEmailTask(MailBean mail){
            this.mail = mail;
        }
        @Override
        public void run() {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(MailUtil.this.sender);
            simpleMailMessage.setTo(this.mail.getRecipient());
            simpleMailMessage.setSubject(this.mail.getSubject());
            simpleMailMessage.setText(this.mail.getContent());
            MailUtil.this.javaMailSender.send(simpleMailMessage);
        }
    }

}
